<template>
  <view class="wanl-page-classify">
    <text class="xptj_title">新品推荐</text>
    <swiper
      class="swiper-container"
      autoplay="false"
      :current="currentSwiper"
      @change="onSwiperChange"
    >
      <!-- 每个 swiper-item 展示三个商品 -->
      <swiper-item v-for="(group, index) in cardGroups" :key="index">
        <view class="card-container">
          <!-- 循环每组中的每一个商品 -->
          <view
            class="card"
            v-for="(item, subIndex) in group"
            :key="subIndex"
            @tap="handleShop(item.id)"
          >
            <!-- 商品图片 -->
            <view class="image-container">
              <image
                class="radius"
                :src="$wanlshop.oss(item.image, 100, 100)"
                mode="aspectFill"
              />
            </view>
            <!-- 商品信息 -->
            <view class="info-container">
              <view class="name">{{ item.title }}</view>
              <view class="details"> 库存:{{ item.stock }} </view>
              <view class="details"> 销量:{{ item.sales }} </view>
              <view class="price-container">
                <text class="price">￥{{ item.price }}</text>
              </view>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>
    <!-- 滑动条 -->
    <view class="progress-container">
      <view class="progress-bar" :style="{ width: progressWidth + '%' }"></view>
    </view>
    <!-- 优惠券 -->
    <scroll-view
      scroll-x="true"
      style="width: 100%"
      class="scroll-containers"
      v-if="mergedCoupons.length > 0"
    >
      <view class="coupon-container">
        <view
          class="coupon"
          v-for="(coupon, index) in mergedCoupons"
          :key="coupon.id"
        >
          <!-- 左边部分，显示金额和提示 -->
          <view class="coupon-left" @click="goToCouponList">
            <text class="coupon-amount"
              ><text class="coupon-amounts">¥</text>
              <template v-if="coupon.type === 'reduction'">{{
                coupon.price
              }}</template>
              <template v-else-if="coupon.type === 'discount'"
                >{{ coupon.discount }}折</template
              >
            </text>
            <view class="coupon-dashed-line"></view>
            <text class="coupon-info">本单可用</text>
          </view>

          <!-- 右边部分，显示有效期和使用按钮 -->
          <view class="coupon-right">
            <view
              class="coupon-desc"
              v-if="coupon.type === 'reduction' || coupon.type === 'discount'"
            >
              <text>{{ coupon.type_text }}</text>
              <view class="coupon-style"></view>
            </view>

            <text
              class="coupon-btn"
              :class="{ claimed: coupon.state, unclaimed: !coupon.state }"
              @click.stop="onReceiveCoupon(index)"
            >
              {{ coupon.state ? "已领取" : "立即领取" }}
            </text>
          </view>
        </view>
      </view>
    </scroll-view>
    <text class="xptj_title">优选商家</text>
    <!-- 横向滚动的商品区域 -->
    <scroll-view class="scroll-container" scroll-x="true" scroll-with-animation>
      <view class="card-containers" :style="{ width: containerWidth + 'rpx' }">
        <!-- 循环展示商品 -->
        <view
          class="cards"
          v-for="(item, index) in Groups"
          :key="index"
          @tap="GroupGoods(item.id)"
        >
          <!-- 商品图片 -->
          <view class="image-containers">
            <image
              class="icons"
              :src="$wanlshop.oss(item.image, 100, 100)"
              mode="aspectFill"
            />
          </view>
          <!-- 商品名称 -->
          <view class="names">{{ item.name }}</view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  name: "WanlPageClassify",
  props: {
    pageData: {
      type: Object,
      default() {
        return {
          name: "分类橱窗",
          type: "classify",
          params: [],
          style: [],
          data: [], // 商品数据
        };
      },
    },
  },
  data() {
    return {
      currentSwiper: 0, // 当前滑块索引
      data: [], // 商品数据
      isModalVisible: false, // 控制模态框从下往上弹出
      selectedItem: {}, // 选择的商品详情
      quantity: 1, // 默认商品数量
      selectedSpec: null, // 用于存储当前选中的规格
      typeWidth: 0, // 类型宽度
      Groups: [],
      containerWidth: 0, // 容器宽度
      current_page: 1,
      mergedCoupons: [], // 存放合并后的优惠券列表
    };
  },
  computed: {
    // 将商品数据每三个划分为一组
    cardGroups() {
      const groups = [];
      for (let i = 0; i < this.data.length; i += 3) {
        groups.push(this.data.slice(i, i + 3)); // 每三个商品一组
      }
      return groups;
    },
    // 计算滑动条的宽度百分比
    progressWidth() {
      if (this.cardGroups.length === 0) return 0;
      return ((this.currentSwiper + 1) / this.cardGroups.length) * 100;
    },
  },
  created() {
    this.getCategory();
    this.loadAllData();
  },
  watch: {
    Groups() {
      // 根据商品数量动态计算容器宽度
      const itemWidth = 130; // 每个商品卡片的宽度 + 间距
      const rows = 2; // 固定为两行显示
      const columns = Math.ceil(this.Groups.length / rows);
      this.containerWidth = columns * itemWidth;
    },
  },
  methods: {
    async loadAllData() {
      await uni.request({
        url: "/wanlshop/page/category",
        data: {
          col: this.pageData.params.colStyle,
          data: JSON.stringify(this.pageData.data),
        },
        success: (res) => {
          this.data = res.data;
        },
      });

      try {
        const [reductionRes, discountRes, platformRes, platforms] =
          await Promise.all([
            this.loadData("reduction"), // 请求满减券
            this.loadData("discount"), // 请求折扣券
            this.loadPlatformData("reduction"), // 请求平台券
            this.loadPlatformData("discount"), // 请求平台券
          ]);

        // 合并满减券和折扣券的数据
        let reductionCoupons = reductionRes.data.data.map((item) => ({
          ...item,
          state: false, // 默认状态
        }));

        let discountCoupons = discountRes.data.data.map((item) => ({
          ...item,
          state: false, // 默认状态
        }));
        // 处理平台券
        let platformCoupons = platformRes.data.data.map((item) => ({
          ...item,
          state: false, // 默认状态
        }));
        let platformsCoupons = platforms.data.data.map((item) => ({
          ...item,
          state: false, // 默认状态
        }));
        // 合并后按 createtime 进行排序
        this.mergedCoupons = [
          ...reductionCoupons,
          ...discountCoupons,
          ...platformCoupons,
          ...platformsCoupons,
        ].sort((a, b) => b.createtime - a.createtime);
        // 截取最多 5 个最新优惠券
        this.mergedCoupons = this.mergedCoupons.slice(0, 5);
      } catch (error) {
        console.error("请求数据时发生错误:", error);
      }
    },

    // 修改 loadData 方法返回 Promise 以便 Promise.all 使用
    loadData(type) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: "/wanlshop/coupon/getList",
          data: {
            type: type, // 传递 type 参数
            page: this.current_page,
          },
          success: (res) => {
            console.log(`${type}优惠券数据:`, res.data.data);
            resolve(res); // 成功时返回数据
          },
          fail: (err) => {
            console.error("接口请求失败:", err);
            reject(err); // 失败时返回错误
          },
        });
      });
    },
    // 请求平台券数据
    loadPlatformData(type) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: "/wanlshop.coupon/getPlatformList",
          data: {
            type: type, // 传递 type 参数
            page: this.current_page,
          },
          success: (res) => {
            console.log(`${type}平台优惠券数据:`, res.data.data);
            resolve(res); // 成功时返回数据
          },
          fail: (err) => {
            console.error("接口请求失败:", err);
            reject(err); // 失败时返回错误
          },
        });
      });
    },
    // 页面跳转到优惠券列表
    goToCouponList() {
      uni.navigateTo({
        url: "/pages/user/coupon/list", // 指定跳转的页面路径
      });
    },

    // 点击立即领取优惠券
    async onReceiveCoupon(index) {
      let coupon = this.mergedCoupons[index];
      uni.request({
        url: "/wanlshop/coupon/receive",
        method: "POST",
        data: { id: coupon.id },
        success: (res) => {
          console.log("响应内容:", res);
          if (res.statusCode === 200) {
            //this.mergedCoupons[index].state = true; // 将状态更新为已领取
            // this.loadAllData();
            this.$wanlshop.msg(res.data.msg || "领取成功");
          } else {
            console.error("服务器返回错误，状态码:", res.statusCode);
            this.$wanlshop.msg("领取失败，请稍后再试");
          }
        },
        fail: (err) => {
          console.error("请求失败:", err);
          this.$wanlshop.msg("网络异常，请检查网络连接");
        },
      });
    },
    // 处理 swiper 切换时触发的事件
    onSwiperChange(event) {
      this.currentSwiper = event.detail.current;
    },

    handleShop(id) {
      // 点击商品事件
      console.log("跳转到商品详情，商品ID: ", id);
      this.$wanlshop.to(`/pages/product/goods?id=${id}`);
    },

    closeModal() {
      this.isModalVisible = false;
    },
    GroupGoods(id) {
      // 点击商品事件
      console.log("跳转到商品详情111，商品ID: ", id);
      this.$wanlshop.to(`pages/category?id=${id}`);
    },
    async getCategory() {
      await uni.request({
        url: "/wanlshop/common/getCategory",
        success: (res) => {
          console.log("分类数据:", res.data.caregotyList);
          this.Groups = res.data.caregotyList;
        },
        fail: (err) => {
          console.error("err", err);
        },
      });
    },
  },
};
</script>

<style>
.wanl-page-classify {
  width: 100%;
}

.xptj_title {
  font-size: 34rpx;
  padding-left: 35rpx;
  font-weight: 700;
}

.swiper-container {
  width: calc(100% - 40rpx); /* 左右各20rpx的外边距 */
  margin-left: 20rpx;
  margin-right: 20rpx;
  margin-top: 20rpx;
  height: 430rpx; /* 适当增加 swiper 的高度 */
  background-color: #fff;
  border-radius: 20rpx;
}

.card-container {
  display: flex;
  justify-content: space-between; /* 每个商品之间均匀分布 */
  padding: 20rpx;
}

.card {
  background-color: #fff;
  border-radius: 15rpx;
  /* box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.1); */
  width: 30%; /* 每个商品占三分之一的宽度 */
  text-align: center;
}
.image-container {
  width: 100%;
  height: 200rpx; /* 调整图片容器的高度 */
  position: relative;
}

.image-container image {
  width: 100%;
  height: 100%;
  background-color: #fff;
  object-fit: cover;
}
.info-container {
  margin-top: 20rpx;
}

.name {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.tag {
  position: absolute;
  top: 5rpx;
  left: 5rpx;
  background-color: orange;
  color: white;
  padding: 5rpx;
  border-radius: 5rpx;
  font-size: 22rpx;
}

.details {
  font-size: 22rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.price-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20rpx;
}
.bottom-section {
  display: flex;
  /* justify-content: space-between; */
  align-items: center;
}

.price {
  font-size: 32rpx;
  color: red;
}

.original-price {
  font-size: 28rpx;
  text-decoration: line-through;
  color: #999;
  margin-left: 10rpx;
}
.progress-container {
  width: calc(100% - 100rpx);
  height: 10rpx;
  background-color: #f1f1f1;
  border-radius: 5rpx;
  margin-left: 50rpx;
  margin-right: 50rpx;
}

.progress-bar {
  height: 100%;
  background-color: #ff4632;
  border-radius: 5rpx;
  transition: width 0.3s ease;
}
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  z-index: 998; /* 让遮罩层在模态框之下 */
}

.cart-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  width: 100%;
  height: 60%;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  box-shadow: 0 -5rpx 15rpx rgba(0, 0, 0, 0.1);
  transform: translateY(100%);
  transition: transform 0.3s ease-in-out;
  z-index: 999; /* 确保模态框在遮罩层上 */
}

.cart-modal.show {
  transform: translateY(0);
}
.cart-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  width: 100%;
  height: 60%; /* 设置模态框高度更高 */
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  box-shadow: 0 -5rpx 15rpx rgba(0, 0, 0, 0.1);
  transform: translateY(100%); /* 初始状态在屏幕下方 */
  transition: transform 0.3s ease-in-out; /* 平滑过渡 */
}

.cart-modal.show {
  transform: translateY(0); /* 显示时移动到屏幕内 */
}

.modal-content {
  padding: 20rpx;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.modal-body {
  display: flex;
  flex-direction: row;
}

.modal-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
}

.modal-info {
  flex: 1;
  margin-left: 20rpx;
}
.modal-info > view {
  margin-bottom: 30rpx; /* 为每个子元素添加下边距 */
}

.modal-stock {
  color: #999;
  font-size: 24rpx;
}
.modal-price {
  color: red;
  font-size: 30rpx;
}
.add-cart-button {
  width: 100%;
  background-color: #3ab34a;
  color: white;
  padding: 20rpx;
  border-radius: 10rpx;
  text-align: center;
  font-size: 24rpx;
}
.modal-quantity {
  display: flex;
  justify-content: space-between;
}
.modal-quantity-button {
  display: flex;
  align-items: center;
}
.modal-quantity-button button {
  height: 40rpx;
  line-height: 40rpx;
  background-color: #fff;
  border: none;
  border-radius: 5rpx;
  font-size: 24rpx;
  color: #333;
}
.modal-spec {
  margin-bottom: 20rpx;
}
.modal-spec view {
  padding: 10rpx 20rpx;
  margin-right: 10rpx;
  border: 1rpx solid #ccc;
  border-radius: 5rpx;
  display: inline-block;
}

.modal-spec view.selected {
  background-color: #3ab34a;
  color: #fff;
  border-color: #3ab34a;
}
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000; /* 确保模态框在最上层 */
}

.preview-image {
  max-width: 90%;
  max-height: 90%;
  border-radius: 10rpx; /* 可选: 圆角效果 */
}
/* 优惠券 */
.scroll-containers {
  overflow-x: scroll; /* 启用横向滚动 */
  display: flex;
  margin: 20rpx;
  border-radius: 20rpx;
  height: 130rpx;
  padding-right: 20rpx;
  white-space: nowrap; /* 禁止换行 */
}
.coupon-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 20rpx;
  margin-right: 20rpx;
  white-space: nowrap; /* 禁止换行 */
  flex-wrap: nowrap; /* 保证在一行显示 */
}

/* 优惠券主体样式 */
.coupon {
  display: flex;
  flex-direction: row;
  background-color: #fff;
  border-radius: 20rpx;
  width: 300rpx;
  height: 110rpx;
  position: relative;
  justify-content: space-between;
  box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.1);
  padding: 10rpx;
  margin-right: 20rpx;
}

/* 优惠券左侧部分 */
.coupon-left {
  flex: 2;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  width: 120rpx;
  height: 90rpx;
  background: linear-gradient(
    to right,
    #fc8709,
    #fe5b31
  ); /* 从左到右的渐变色 */
  border-radius: 10rpx;
  margin-right: 30rpx;
  padding: 10rpx;
}

.coupon-amount {
  font-size: 30rpx;
  font-weight: bold;
  color: #fff;
  font-family: "Poppins", sans-serif;
}
.coupon-amounts {
  font-size: 20rpx;
  font-weight: normal;
  color: #fff;
}
.coupon-dashed-line {
  width: 100%; /* 虚线宽度自适应 */
  height: 0;
  border-bottom: 2rpx dashed #fff; /* 虚线样式 */
  margin-left: 20rpx; /* 两端凹回 */
  margin-right: 20rpx; /* 两端凹回 */
  box-sizing: border-box; /* 确保 padding/margin 不影响总宽度 */
}
.coupon-info {
  font-size: 22rpx;

  color: #fff;
}

/* 分隔线 */
/* .coupon-divider {
  width: 1rpx;
  background-color: #fff;
  margin: 0 20rpx;
} */

/* 优惠券右侧部分 */
.coupon-right {
  /* flex: 3; */
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: flex-start;
  margin-right: 20rpx;
}

.coupon-desc {
  font-size: 26rpx;
  color: #333;
  position: relative;
}
.coupon-desc text {
  position: relative;
  z-index: 10;
  text-align: center;
  line-height: 22rpx;
}
.coupon-style {
  position: absolute;
  bottom: -5rpx;
  left: -1rpx;
  z-index: 1;
  width: 80rpx;
  height: 22rpx;
  background: linear-gradient(to right, #ffdcbd, #ff7118);
  border-radius: 30rpx;
}
.coupon-descs {
  font-size: 22rpx;
  color: #333;
}
.coupon-btn {
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #999;
  background-color: transparent;
  padding: 5rpx 10rpx;
  border-radius: 10rpx;
  cursor: pointer;
}
/* 未领取按钮的样式 */
.coupon-btn.unclaimed {
  background-color: #f43300;
  color: #fff;
  padding: 5rpx 10rpx;
  border-radius: 10rpx;
  cursor: pointer;
}

/* 已领取后的样式 */
.coupon-btn.claimed {
  background-color: white;
  color: #ff7118;
  border: 1rpx solid #ff7118;
  padding: 5rpx 10rpx;
  border-radius: 10rpx;
}
/* 优选商家 */
.scroll-container {
  width: calc(100% - 40rpx);
  height: 320rpx; /* 调整为两行商品的高度 */
  margin: 20rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow-x: scroll;
}

.card-containers {
  display: flex;
  flex-wrap: wrap;
  height: 100%;
}

.cards {
  width: 130rpx; /* 卡片宽度 */
  margin: 10rpx;
  display: flex;
  flex-direction: column; /* 纵向排列图片和文字 */
  align-items: center; /* 水平居中 */
}

.image-containers {
  width: 100rpx;
  height: 100rpx;
  background-color: #ccda16;
  border-radius: 50%;
  overflow: hidden;
}

.icons {
  width: 100%;
  height: 100%;
}

.names {
  font-size: 26rpx;
  margin-top: 5rpx;
  text-align: center; /* 水平居中 */
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  height: 40rpx; /* 设置文字区域高度 */
  line-height: 40rpx; /* 单行文字居中 */
  white-space: nowrap; /* 防止文字换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 超出部分省略号显示 */
}
</style>
